package com.bw.message

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.pm.PackageManager
import android.media.RingtoneManager
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.DeviceUtils.isEmulator
import com.bw.lib_base.base.BaseFragment
import com.bw.message.adapter.MessageAdapter
import com.bw.message.databinding.FragmentMessageBinding
import com.bw.message.databinding.ItemMessageBinding
import com.bw.message.entity.MessageData
import com.bw.message.model.MessageViewModel
import dagger.hilt.android.AndroidEntryPoint

import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MessageFragment : BaseFragment<FragmentMessageBinding,MessageViewModel>() {

    private lateinit var messageAdapter: MessageAdapter
    val accessId = "b91600d72125480f9502a98491f0839c"
    val userId = 1
    // 在Fragment中添加
    private val vibrationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (!isGranted) {
            binding.messageSwitch3.isChecked = false
            Toast.makeText(context, "振动功能需要振动权限", Toast.LENGTH_SHORT).show()
        }
    }

    override fun setupUI() { //初始化ui
        binding.messageRv.apply {
            messageAdapter= MessageAdapter()
            layoutManager =LinearLayoutManager(context)
            binding.messageRv.adapter=messageAdapter
        }

    }

    override fun fetchData() { // 获取数据
        vm.getMessageData(accessId, userId)

    }

    override fun observeData() { // 监听数据
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                vm.messageData.collect { messages ->
                    messages?.let {
                        val previousCount = messageAdapter.itemCount
//                        messageAdapter.data.clear()
                        messageAdapter.data.addAll(it)
                        messageAdapter.notifyDataSetChanged()
                        // 滚动到最后一条消息
                        binding.messageRv.scrollToPosition(messageAdapter.itemCount - 1)
// 如果是新消息且数量增加
                        if (it.isNotEmpty() && it.size > previousCount) {
                            showMessageNotification(it.last())
                        }

                    }
                }


            }


        }

    }


    override fun onDestroyView() {
        super.onDestroyView()
        // 断开WebSocket连接
        vm.disconnect()
    }
    override fun handleEvent() { // 处理事件
    }

    override val mLayoutResId: Int
        get() = TODO("Not yet implemented")

    override fun lazyLoad() { // 懒加载
        TODO("Not yet implemented")
    }

    private fun playNotificationSound() {
        try {
            // 获取系统默认通知音效的URI
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            // 使用获取的URI创建Ringtone实例
            val ringtone = RingtoneManager.getRingtone(requireContext(), soundUri)
            // 播放通知音效
            ringtone.play()
        } catch (e: Exception) {
            Log.e("MessageFragment", "播放通知音效失败", e)
        }
    }

    private fun showMessageNotification(message: MessageData) {
        binding.messageSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                // 启动WebSocket连接
                vm.sendMessage("1")
                binding.notificationBanner.visibility = View.VISIBLE
                binding.notificationText.text = message.messageContent
                // 设置图标（根据消息类型）
                val iconRes = when (message.messageStatus) {
                    "已读" -> R.drawable.item_message_img
                    "处理中" -> R.drawable.item_message_img2
                    "已过期" -> R.drawable.item_message_img3
                    else -> {
                        R.drawable.item_message_img
                    }
                }
                binding.notificationImage.setImageResource(iconRes)
            } else {
                vm.sendMessage("66666")
            }
        }
        binding.messageSwitch2.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                // 启动WebSocket连接
                vm.sendMessage("2")
                playNotificationSound()
            } else {
                vm.sendMessage("77777")
            }
        }
        binding.messageSwitch3.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                // 启动WebSocket连接
                vm.sendMessage("3")
                 vibrate()
            } else {
                vm.sendMessage("8888")
            }
        }
        // 3秒后自动隐藏
        binding.notificationBanner.postDelayed({
            binding.notificationBanner.visibility = View.GONE
        }, 3000)

        // 点击横幅立即隐藏
        binding.notificationBanner.setOnClickListener {
            binding.notificationBanner.visibility = View.GONE
        }
    }



    private fun vibrate() {
        try {
            // 检查权限和振动器可用性
            if (ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.VIBRATE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                // 根据API级别获取Vibrator实例
                val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    val vibratorManager = requireContext().getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
                    vibratorManager.defaultVibrator
                } else {
                    requireContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                }
                // 旧版本简单振动
                if (vibrator.hasVibrator()) {
                    // 根据API级别选择振动模式
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        // 更丰富的振动效果
                        vibrator.vibrate(
                            VibrationEffect.createWaveform(
                                longArrayOf(0, 100, 100, 100), // 等待0ms,振动100ms,暂停100ms,振动100ms
                                intArrayOf(0, 150, 0, 200),    // 对应的振动强度
                                -1 // 不重复
                            )
                        )
                    } else {
                        vibrator.vibrate(200) // 旧版本简单振动
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("Vibration", "振动失败: ${e.message}")
        }
    }



}